﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Markup;
using System.Windows.Data;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows;

namespace Halfwit.Converters
{
    public class StatusSourceConverter : MarkupExtension, IValueConverter
    {
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }

        private static Regex _linkRegex = new Regex("<a href=\\\"([^\\\"]+)\\\" rel=\\\"nofollow\\\">([^\\<]+)", RegexOptions.Compiled);

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var s = value as string;
            if (s == null) return string.Empty;

            var textBlock = new TextBlock();
            textBlock.Inlines.Add(" from ");

            var link = new Hyperlink();

            if (s == HalfwitConstants.SearchResultSource)
            {
                link.TextDecorations = null;
                link.Inlines.Add("search");
                link.Focusable = false;
                link.ToolTip = "Load the original tweet (Backspace)";
                link.SetBinding(Hyperlink.CommandProperty,
                    new Binding { ElementName = "me", Path = new PropertyPath("DataContext.FindSource") });
                link.SetBinding(Hyperlink.CommandParameterProperty, new Binding());
                textBlock.Inlines.Add(link);

                return textBlock;
            }

            s = System.Web.HttpUtility.UrlDecode(s);

            var match = _linkRegex.Match(s);
            if (match.Groups.Count < 3) return null;

            var uri = match.Groups[1].Value;
            var name = match.Groups[2].Value;

            link.TextDecorations = null;
            link.Inlines.Add(name);
            link.SetBinding(Hyperlink.CommandProperty,
                new Binding { ElementName = "me", Path = new PropertyPath("DataContext.NavigateToUrl") });
            link.CommandParameter = uri;
            textBlock.Inlines.Add(link);

            return textBlock;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
